package com.gengzp.mq.common.utils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.*;

/**
 * @ClassName GengzpMqIpUtils
 * @Description 消息队列模块ip获取工具类
 * @Author gengzp
 * @Date 2025/7/10 17:26
 */
public class GengzpMqIpUtils {

    // 备选 IP 查询服务
    private static final String[] IP_SERVICES = {
            "https://api.ipify.org",
            "https://icanhazip.com",
            "https://ident.me",
            "https://ifconfig.co/ip"
    };

    /**
     * 获取当前服务的公网IP
     *
     * @return 公网ip
     */
    public static String getPublicIp() {
        try {
            String result = "unknown";

            // 创建支持TLS 1.3/1.2的HTTP客户端
            HttpClient secureClient = createSecureClient();

            for (String ipUrl : IP_SERVICES) {
                try {
                    HttpRequest request = HttpRequest.newBuilder()
                            .uri(URI.create(ipUrl))
                            .header("User-Agent", "Java HttpClient")
                            .GET()
                            .build();
                    result = secureClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
                    break;
                } catch (Exception ignored) {
                }
            }

            return result;
        } catch (Exception e) {
            return "unknown";
        }
    }

    private static HttpClient createSecureClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
        // 创建默认信任管理器
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

        // 创建支持TLS 1.3和1.2的SSL上下文
        SSLContext sslContext = SSLContext.getInstance("TLSv1.3");
        sslContext.init(null, trustManagers, new SecureRandom());

        // 获取默认支持的密码套件并选择常用的
        String[] defaultCipherSuites = sslContext.getDefaultSSLParameters().getCipherSuites();

        // 配置SSL参数
        SSLParameters sslParameters = new SSLParameters();
        sslParameters.setProtocols(new String[]{"TLSv1.3", "TLSv1.2"});
        sslParameters.setCipherSuites(defaultCipherSuites);

        return HttpClient.newBuilder()
                .sslContext(sslContext)
                .sslParameters(sslParameters)
                .followRedirects(HttpClient.Redirect.NORMAL)
                .build();
    }

}
